//
//  DataUtil.m
//  XYTest
//
//  Created by yao zhaofeng on 2018/4/17.
//  Copyright © 2018年 YaoZhaofeng. All rights reserved.
//

#import "DataUtil.h"

@implementation DataUtil
+ (void)saveDataByNSUserDefaults:(id)data forKey:(NSString *)key {
    NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:@"group.xy.3DTouch"];
    [shared setObject:data forKey:key];
    [shared synchronize];
}

+ (id)readDataFromNSUserDefaultsForKey:(NSString *)key {
    NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:@"group.xy.3DTouch"];
    return [shared valueForKey:key];
}

+ (BOOL)saveDataByNSFileManager:(NSString *)data ForPath:(NSString *)path {
    NSError *error = nil;
    NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.xy.3DTouch"];
    containerURL = [containerURL URLByAppendingPathComponent:path];
    
    BOOL result = [data writeToURL:containerURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
    
    if (!result) {
        NSLog(@"%@",error);
    } else {
        NSLog(@"save value:%@ success.",data);
    }
    
    return result;
}
+ (NSString *)readDataByNSFileManagerForPath:(NSString *)path {
    NSError *error = nil;
    NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.xy.3DTouch"];
    containerURL = [containerURL URLByAppendingPathComponent:path];
    NSString *value = [NSString stringWithContentsOfURL:containerURL encoding:NSUTF8StringEncoding error:&error];
    
    return value;
}

+ (NSString *)valueForKey:(NSString *)key
           fromQueryItems:(NSArray *)queryItems
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key];
    NSURLQueryItem *queryItem = [[queryItems
                                  filteredArrayUsingPredicate:predicate]
                                 firstObject];
    return queryItem.value;
}
@end
